﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Comm;

namespace CJGL
{
   public static class Three
    {
        static string Appid = "z001291";
        static string appsecret = "2d953354b03fc633d8f1767f601dd86c";
        static string appsture = "05d4a9553f27171151ce8298ed31251f";
        static string url= "https://www.qgfw315.com/yuebucjapi/";
        static string token = "";
        
        //获取token
        public static string login()
        {
            string nowurl = url + "login";
            LoginModel model = new LoginModel();
            model.Appid = Appid;
            model.Appsecret = appsecret;
            model.Czuser = "kbn01";
           // model.Czuser = "test01";
            model.Ttamp = GetTimeStamp();
            model.Sture = GetMd5(model.Appsecret + appsture + model.Ttamp.ToString())   ;
            string par = JsonConvert.SerializeObject(model);
            string reMes = Post(nowurl, par);
            if (reMes != ""){

                try
                {
                    ReturnModel returnModel= JsonConvert.DeserializeObject<ReturnModel>(reMes);
                    if (returnModel.code == 0) {
                        token = returnModel.data.token;
                        return "";
                    }
                    else
                    {
                        return ("获取toekn失败，返回数据" + reMes);
                    }
                   
                }
                catch(Exception ex)
                {
                    return ("获取toekn失败，返回数据"+ reMes);
                }
            }
            return "未获取到toekn";

        }


        //获取产品列表
        public static List<DataItem> GetpPoduct(int page,string keyword, int isRdo=0)
        {
            String mes = "";
            if (token == "")
            {
               string loginStr= login();
                if (loginStr != "")
                {
                    WriteFileCls.InserLog("获取toekn失败 " + loginStr);
                    return null;
                }
            }


            string nowurl = url + "getproduct";
            ProductRequstModel model = new ProductRequstModel();
            model.Token = token;
            model.keyword = keyword;
            model.Ttamp = GetTimeStamp();
            model.Page = page;
            model.Sture = GetMd5(model.Token + appsture + model.Ttamp.ToString());
            string par = JsonConvert.SerializeObject(model);
            string reMes = Post(nowurl, par);
            if (reMes != "")
            {
                try
                {
                    ResProduct returnModel = JsonConvert.DeserializeObject<ResProduct>(reMes);
                    if (returnModel.code == 0)
                    {
                        return returnModel.data;
                    }
                    else if(returnModel.code == 10000)
                    {
                        string loginStr = login();
                        if (loginStr != "")
                        {
                            WriteFileCls.InserLog("获取toekn失败 " + loginStr);
                            return null;
                        }
                        if (isRdo == 0)
                        {
                            GetpPoduct(page, keyword,1);
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }

                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            return null;
        }


        //添加关联关系
        public static string AddRelation(AddRelationMode model, int isRdo = 0)
        {
            bool isok = false;
            String mes = "";
            if (token == "")
            {
                string loginStr = login();
                if (loginStr != "")
                {
                    WriteFileCls.InserLog("获取toekn失败 " + loginStr);
                    return "获取toekn失败 " + loginStr;
                }
            }


            string nowurl = url + "addrelation";
            model.token = token;
            model.scanmode = 1;
            model.ttamp = GetTimeStamp();
            model.sture = GetMd5(model.token + appsture + model.ttamp.ToString());
            string par = JsonConvert.SerializeObject(model);
            string reMes = Post(nowurl, par);
            if (reMes != "")
            {
               
                    AddRoot returnModel = JsonConvert.DeserializeObject<AddRoot>(reMes);
                    if (returnModel.code == 0)
                    {
                        return "";
                    }
                    else if (returnModel.code == 10000)
                    {
                        string loginStr = login();
                        if (loginStr != "")
                        {
                            WriteFileCls.InserLog( loginStr);
                            return loginStr;
                        }
                        if (isRdo == 0)
                        {
                            AddRelation(model, 1);
                        }
                        else
                        {
                            return loginStr;
                        }
                    }
                    else
                    {
                        return returnModel.msg;
                    }

               
            }
            return "上传失败返回空";
        }

        //MD5
        private static string GetMd5(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();


            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }


            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="isMillisecond">是否毫秒</param>
        /// <returns>当前时间戳</returns>
        private static long GetTimeStamp(bool isMillisecond = false)
        {
            var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var timeStamp = isMillisecond ? Convert.ToInt64(ts.TotalMilliseconds) : Convert.ToInt64(ts.TotalSeconds); return timeStamp;
        }


        private static string Post(string PostUrl, string Parameters)
        {
            string content = string.Empty;
            try
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
               // ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                //跳过ssl验证
                //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                //path不是登录界面，是登录界面向服务器提交数据的界面
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(PostUrl);
                myReq.Method = "Post";
                myReq.ContentType = "application/json";
                //myReq.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());	//https添加 Basic auth验证
                ////myReq.Connection = "keep-alive";
                //myReq.Headers.Add("Cookie", "477cadb5a1f917cda5f5d9cab20f8841=42c7f20d7a509babe62c3e74995d5140; 3c343960f5dd4584c34cd6b38885cefe=000e1bf2bbd8e5ae2dabff0eb27e3b6f");
                //myReq.Headers.Add("usercode", "JRFZCX_MYFK");
                //myReq.Headers.Add("password", "*&ZHY&*0379");//&JRFZ&01
                //填充POST数据
                if (Parameters != null)
                {
                    //转换为字节数组
                    byte[] bytesRequestData = Encoding.UTF8.GetBytes(Parameters);
                    myReq.ContentLength = bytesRequestData.Length;
                    Stream requestStream = myReq.GetRequestStream();
                    requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                    requestStream.Close();
                }
                else
                {
                    myReq.ContentLength = 0;
                }

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                //获取服务器返回信息
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader reader = new StreamReader(myStream, Encoding.UTF8);
                content = reader.ReadToEnd();
                reader.Close();
                HttpWResp.Close();
            }
            catch (Exception ex)
            {
                content = ex.ToString();
            }
            return content;
        }



    }
}
